import React, { useState } from 'react';
import GopherProps from '../objects/internal/GopherProps';
import './AnalysisFragment.css';
import OrderFilter from '../components/OrderFilter';
import { Card, Spin, Typography, Row, Col } from 'antd';
import { useTranslation } from 'react-i18next';
import { OrderFilterCondition } from '../objects/internal/OrderFilterCondition';
import { applyOrderFilter } from '../pouch/HyperFilter';
import { Order } from '../pouch/models/Order';
import OrderStatePieChart from '../components/charts/OrderStatePieChart';
import MileageHistogram from '../components/charts/MileageHistogram';

export default function AnalysisFragment(props: GopherProps) {
	const {t} = useTranslation();

	const [loading, setLoading] = useState(false);
	const [queryInitiated, setQueryInitiated] = useState(false);
	const [orderData, setOrderData] = useState<Order[]>([]);

	const onFilter = (filter: OrderFilterCondition) => {
		setLoading(true);
		applyOrderFilter(props.gopher, filter).then(result => {
			console.log(result.length);
			setOrderData(result);
			setQueryInitiated(true);
			setLoading(false);
		});
	};

	let child;
	if (queryInitiated) {
		child = (<>
			<Row>
				<Col span={6}>
					<OrderStatePieChart orders={orderData} />
				</Col>
				<Col span={6}>
					<MileageHistogram orders={orderData} />
				</Col>
			</Row>
		</>);
	} else {
		child = loading ? <Spin /> : <Typography>{t('text-analysis-toast')}</Typography>;
	}

	return (
		<div className={'analysis-wrapper'}>
			<div className={'analysis-component-wrapper'}>
				<OrderFilter onSubmitButtonPressed={onFilter} gopher={props.gopher} keepAllOptions={true} />
			</div>
			<div className={'analysis-component-wrapper'}>
				<Card>
					{child}
				</Card>
			</div>
		</div>
	);
}
